package com.seu.dm.controllers;

import com.seu.dm.dto.UserBaseDTO;
import com.seu.dm.entities.Comment;
import com.seu.dm.entities.Order;
import com.seu.dm.services.CommentService;
import com.seu.dm.services.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Greeting on 2017/2/28.
 */
@Controller
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private OrderService orderService;

    /**
     * 得到当前商品的所有评价
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/getComments")
    public String getComments(@PathVariable Integer id,Model model){
        List<Comment> comments = commentService.findCommentsByProductId(id);
        model.addAttribute("comments",comments);
        return "product/product_detail";
    }

    @RequestMapping(value = "/addComment/{orderId}")
    public String addComment(@PathVariable Integer orderId,@RequestParam(value = "comment") String text, HttpServletRequest request,Model model){
        //Boolean isCommented = false;
        HttpSession httpSession = request.getSession();
        UserBaseDTO userBase = (UserBaseDTO)httpSession.getAttribute("userBase");
        Integer buyerId = userBase.getId();

        Order order = orderService.findOrder(orderId);
        Comment comment = new Comment();
        comment.setBuyerId(buyerId);
        comment.setOrderId(orderId);
        comment.setProductId(order.getProduct().getId());
        comment.setSeller(order.getSeller());
        comment.setText(text);

        commentService.addComment(comment);
        String url = request.getRequestURL().toString();
//        List<Comment> comments = commentService.findCommentsByProductId(order.getProduct().getId());
//        for (Comment commentIter : comments) {
//            if(commentIter.getBuyerId() == buyerId) isCommented = true;
//        }

        model.addAttribute("message","评价成功!");
        model.addAttribute("jumpUrl",url);
//        model.addAttribute("isCommented",isCommented);
        return "common/alert";
     }
}
